package com.jnu.keepaccounts.history;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;
import com.jnu.keepaccounts.R;
import com.jnu.keepaccounts.data.Data;
import com.jnu.keepaccounts.data.DataBank;
import com.jnu.keepaccounts.data.DataTiaoMu;
import com.jnu.keepaccounts.data.DataTou;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link MonthFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class MonthFragment extends Fragment {
    private View view;
    private TextView textView,textView1,textView2;
    private BarChart barChart1;
    private LinearLayout linearLayout;
    private ArrayList<Data> datas = new ArrayList<>();
    private ArrayList<DataTiaoMu> dataTiaoMuszhi = new ArrayList<>();
    private ArrayList<DataTiaoMu> dataTiaoMusshou = new ArrayList<>();
    private ArrayList<Double> doubleszhi = new ArrayList<>();
    private ArrayList<Double> doublesshou = new ArrayList<>();
    private RecyclerView recyclerView;
    private MyNewAdapter myAdapter;
    private DataBank dataBank ;
    final int[] month = new int[1];
    final int[] year = new int[1];
    private double max=0,min = 0;
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public MonthFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment MonthFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static MonthFragment newInstance(String param1, String param2) {
        MonthFragment fragment = new MonthFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }

    }


    @SuppressLint("WrongConstant")
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_month, container, false);

        //linearLayout = view.findViewById(R.id.linearLayout_tongji);
        dataBank = new DataBank(getContext());
        Calendar calendar = Calendar.getInstance();

        month[0] = calendar.get(Calendar.MONTH) + 1;

        year[0] = calendar.get(Calendar.YEAR);

        textView = view.findViewById(R.id.history_date);
        textView1 = view.findViewById(R.id.history_ab_date);

        myAdapter = new MyNewAdapter(datas);
        textView2 = view.findViewById(R.id.empty_text);
        refresh(year[0],month[0],view);


        ImageButton button_last = view.findViewById(R.id.last);
        button_last.setOnClickListener(v -> {
            month[0] -= 1;
            if(month[0] == 0){
                year[0] -= 1;
                month[0] = 12;
            }
            refresh(year[0],month[0],view);
        });
        ImageButton button_next = view.findViewById(R.id.next);
        button_next.setOnClickListener(v -> {
            month[0] += 1;
            if(month[0] == 13){
                year[0] += 1;
                month[0] = 1;
            }
            refresh(year[0],month[0],view);
        });

//        datas.clear();
//        for(Data data:dataBank.loadData()){
//            if(data.getMonth()==month[0]&&data.getYear() == year[0]){
//                datas.add(data);
//            }
//        }

        recyclerView = view.findViewById(R.id.recyclerView_month);

        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(layoutManager);

        recyclerView.setAdapter(myAdapter);

        return view;
    }
//    private void initBarChart(View view) {
//        barChart1 = view.findViewById(R.id.bar_chart1);
//        barChart1.clear();
//        barChart1.getDescription().setEnabled(false);//不显示描述
//        barChart1.setExtraOffsets(10,10,10,10);
//        datadeal();
//        setAxis();
//        setTuData();
//    }
//
//    private void datadeal(){
//        dataTiaoMuszhi.clear();
//        dataTiaoMusshou.clear();
//        max = min = 0;
//        for(Data data:datas){
//            if(data.getFlag() == 2 ){
//                if(Math.abs(((DataTou)data).getZhi())+((DataTou)data).getZhi()>max){
//                    max = Math.abs(((DataTou)data).getZhi())+((DataTou)data).getZhi();
//                }
//                if(Math.abs(((DataTou)data).getZhi())+((DataTou)data).getZhi()<min){
//                    min = Math.abs(((DataTou)data).getZhi())+((DataTou)data).getZhi();
//                }
//                dataTiaoMusshou.add(0,new DataTiaoMu(1,0,null,0,null,data.getYear(),data.getMonth(),data.getDay(),0,0L));
//                dataTiaoMuszhi.add(0,new DataTiaoMu(1,0,null,0,null,data.getYear(),data.getMonth(),data.getDay(),0,0L));
//            }
//            else {
//                DataTiaoMu tem;
//                if(((DataTiaoMu)data).getShuE()>0){
//                    tem = dataTiaoMusshou.get(0);
//                    tem.setShuE(tem.getShuE()+((DataTiaoMu)data).getShuE());
//                }
//                else {
//                    tem = dataTiaoMuszhi.get(0);
//                    tem.setShuE(tem.getShuE()+((DataTiaoMu)data).getShuE());
//                }
//            }
//        }
//    }
//    private void setTuData() {
//        List<BarEntry> barEntries1 = new ArrayList<>();
////        for(int i = 0;i<dataTiaoMusshou.size();i++){
////            barEntries1.add(new BarEntry(i, new float[]{(float) dataTiaoMusshou.get(i).getShuE() ,(float) -dataTiaoMuszhi.get(i).getShuE()}));
////        }
//        barEntries1.add(new BarEntry(0,new float[]{100,500}));
//        BarDataSet barDataSet1 = new BarDataSet(barEntries1,"");
//        List<Integer> colors = new ArrayList<>();
//        colors.add(Color.RED);
//        colors.add(Color.GREEN);
//        barDataSet1.setColors(colors);
//
//        BarData barData = new BarData(barDataSet1);
//        barData.setBarWidth(0.4f);
//        barChart1.setData(barData);
//
////        List<BarEntry> barEntries1 = new ArrayList<>();
////        barEntries1.add(new BarEntry(0,150000000f));
//////        for(int i = 0;i<dataTiaoMusshou.size();i++){
//////            barEntries1.add(new BarEntry(i, (float) (dataTiaoMusshou.get(i).getShuE()-dataTiaoMuszhi.get(i).getShuE())));
//////        }
////        BarDataSet barDataSet = new BarDataSet(barEntries1,"");
////        BarData barData = new BarData(barDataSet);
////        barChart1.setData(barData);
//    }
//
//    private void setAxis() {
//        if(datas.size()>0){
//            XAxis xAxis = barChart1.getXAxis();
//            xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
//            xAxis.setLabelCount(1);
////            xAxis.setLabelCount(dataTiaoMusshou.size());
////            xAxis.setValueFormatter(new IAxisValueFormatter() {
////                @Override
////                public String getFormattedValue(float value, AxisBase axis) {
////                    if((int)value<dataTiaoMusshou.size()){
////                        return dataTiaoMusshou.get((int) value).getMonth()+"-"+dataTiaoMusshou.get((int) value).getDay()+"";
////                    }
////                    else return "";
////                }
////            });
////            xAxis.setYOffset(10);
//
//            YAxis yAxis_left = barChart1.getAxisLeft();
//            yAxis_left.setAxisMaximum((float) max);
//            yAxis_left.setAxisMinimum((float) min);
//
//
//            YAxis yAxis_right = barChart1.getAxisRight();
//            yAxis_right.setAxisMaximum((float) max);  // 设置y轴的最大值
//            yAxis_right.setAxisMinimum((float) min);  // 设置y轴的最小值
//            yAxis_right.setEnabled(false);  // 不显示右边的y轴
//
//        }
//    }

    private void refresh(int year,int month,View view){
        setDate(year,month );
        //initBarChart(view);
    }
    public void setDate(int year,int month){
        textView.setText(month+"月"+" "+year);
        if(month == 2){
            GregorianCalendar gregorianCalendar = new GregorianCalendar();
            if(gregorianCalendar.isLeapYear(year)){
                textView1.setText(year+"-"+month+"-"+"01至"+year+"-"+month+"-29");
            }
            else textView1.setText(year+"-"+month+"-"+"01至"+year+"-"+month+"-28");
        }
        else if(month ==1||month == 3||month ==5||month ==7||month ==8||month ==10||month ==12){
            textView1.setText(year+"-"+month+"-"+"01至"+year+"-"+month+"-31");
        }
        else textView1.setText(year+"-"+month+"-"+"01至"+year+"-"+month+"-30");
        setData();
    }
    @SuppressLint("WrongConstant")
    public void setData(){
        dataBank = new DataBank(getContext());
        datas.clear();
        for(Data data:dataBank.loadData()){
            if(data.getMonth()==month[0]&&data.getYear() == year[0]){
                datas.add(data);
            }
        }
        if(datas.size() == 0 ){
            textView2.setVisibility(0);
        //linearLayout.setVisibility(8);
        }
        else {
            textView2.setVisibility(8);
            //linearLayout.setVisibility(0);
        }
        myAdapter.notifyDataSetChanged();
    }
    public class MyNewAdapter extends RecyclerView.Adapter<MyNewAdapter.ViewHolder>{
        ArrayList<Data> datas;

        MyNewAdapter(ArrayList<Data> datas){
            this.datas = datas;
        }
        public int getItemViewType(int position){
            return datas.get(position).getFlag();
        }
        @NonNull
        @Override
        public MyNewAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            if(viewType==2)return new MyNewAdapter.TouHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.tou,parent,false));
            else return new MyNewAdapter.TiaoMuHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.tiaomu,parent,false));
        }

        @SuppressLint("WrongConstant")
        @Override
        public void onBindViewHolder(@NonNull MyNewAdapter.ViewHolder holder, int position) {
            Data data = datas.get(position);
            if(data.getFlag()==2){

                DataTou dataTou = (DataTou)data;
                MyNewAdapter.TouHolder touHolder = (MyNewAdapter.TouHolder)holder;
                touHolder.date.setText(dataTou.getYear()+"-"+ dataTou.getMonth()+"-"+dataTou.getDay()+"");
                touHolder.shou.setText(dataTou.getShou()+"");
                touHolder.zhi.setText(Math.abs(dataTou.getZhi())+"");
            }
            else {
                DataTiaoMu dataTiaoMu = (DataTiaoMu) data;
                MyNewAdapter.TiaoMuHolder tiaoMuHolder = (MyNewAdapter.TiaoMuHolder) holder;
                tiaoMuHolder.image.setImageResource(dataTiaoMu.getImage());
                tiaoMuHolder.xiangmu.setText(dataTiaoMu.getXiangMu());
                tiaoMuHolder.laiyuan.setText(dataTiaoMu.getLaiYuan());
                tiaoMuHolder.shue.setText(dataTiaoMu.getShuE()+"");
                if(dataTiaoMu.getYusuan() == 1){
                    tiaoMuHolder.yusuan.setVisibility(0);
                }
            }
        }

        @Override
        public int getItemCount() {
            return datas.size();
        }

        public class ViewHolder extends RecyclerView.ViewHolder {
            public ViewHolder(@NonNull View itemView) {
                super(itemView);
            }
        }
        public class TouHolder extends MyNewAdapter.ViewHolder {
            TextView date;
            TextView shou;
            TextView zhi;

            public TouHolder(@NonNull View itemView) {
                super(itemView);
                date = (TextView) itemView.findViewById(R.id.textview_date);
                shou = (TextView) itemView.findViewById(R.id.textview_shou);
                zhi = (TextView) itemView.findViewById(R.id.textview_zhi);
            }
        }
        public class TiaoMuHolder extends MyNewAdapter.ViewHolder {
            ImageView image,yusuan;
            TextView xiangmu, laiyuan, shue;

            public TiaoMuHolder(@NonNull View itemView) {
                super(itemView);
                image = (ImageView) itemView.findViewById(R.id.imageview);
                xiangmu = (TextView) itemView.findViewById(R.id.textview_xiangmu);
                laiyuan = (TextView) itemView.findViewById(R.id.textview_laiyuan);
                shue = (TextView) itemView.findViewById(R.id.textview_shue);
                yusuan = (ImageView) itemView.findViewById(R.id.yusuan);
            }
        }
    }
}